import wsgiref.handlers
import uuid
import cgi
import os
import xmlutils

from xml.etree.ElementTree import Element, ElementTree
from formencode import validators

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import template

import model

class List(webapp.RequestHandler):
  def get(self):

    artists = db.GqlQuery("SELECT * FROM Artist ORDER BY name")

    template_values = {'artists': artists}

    path = os.path.join(os.path.dirname(__file__), 'templates/artist_list.html')
    self.response.out.write(template.render(path, template_values))

class New(webapp.RequestHandler):
  def get(self):

    template_values = {}

    path = os.path.join(os.path.dirname(__file__), 'templates/artist_new.html')
    self.response.out.write(template.render(path, template_values))

class Add(webapp.RequestHandler):
  def post(self):

    # Determine the properties of the artist entity	  
    artist_name = self.request.get('name')
    artist_uuid = str(uuid.uuid4())

    # Make sure artist_name is not empty
    validators.NotEmpty().to_python(artist_name)

    # Create a new artist entity and save it in the Datastore 
    artist = model.Artist(name=artist_name, uuid=artist_uuid)
    artist.put()

    # Display the newly created artist entity
    self.redirect('/artist/view?uuid=' + artist.uuid)

class Export(webapp.RequestHandler):
  def get(self):

    uuid = self.request.get('uuid')

    artists = db.GqlQuery("SELECT * FROM Artist WHERE uuid = :1", uuid)
    artist = artists.get()    

    artistElement = Element('artist')
    artistElement.attrib["uuid"] = artist.uuid

    nameElement = Element('name')
    nameElement.text = artist.name
    artistElement.append(nameElement)

    createdElement = Element('created')
    createdElement.text = str(artist.created)
    artistElement.append(createdElement)

    self.response.headers["Content-Type"] = "application/xml"
    self.response.headers["Content-disposition"] = "attachment; filename=artist.xml";
    xmlutils.indent(artistElement)
    ElementTree(artistElement).write(self.response.out)

class View(webapp.RequestHandler):
  def get(self):
    uuid = self.request.get('uuid')
    artists = db.GqlQuery("SELECT * FROM Artist WHERE uuid = :1 LIMIT 1", uuid).fetch(1)
    artist = artists[0]
    recordings = db.GqlQuery("SELECT * FROM Recording where artist = :1 ORDER BY title", artist.key())

    template_values = {'artist' : artist, 'recordings' : recordings}

    path = os.path.join(os.path.dirname(__file__), 'templates/artist_view.html')
    self.response.out.write(template.render(path, template_values))

def main():
  application = webapp.WSGIApplication( [
    ('/artist/list', List), 
    ('/artist/new', New), 
    ('/artist/add', Add), 
    ('/artist/view', View), 
    ('/artist/export', Export)
  ], debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()

